#include "../main.h"

void init_decoder()
{
    pthread_mutex_init(&peer_decode_mutex, NULL);
}

void decode(int sockfd, char *msg, int len)
{
    if (len > 0)
    {
        pthread_mutex_lock(&peer_decode_mutex);
        char *data = charCopy(msg, len);
        addToMap(msgmap, sockfd, msg, len);
        free(data);
        data = NULL;
        MNode *node = getbykey(msgmap, sockfd);
        parse_node(node);
        pthread_mutex_unlock(&peer_decode_mutex);
    }
}

void parse_node(MNode *curNode)
{
    RecvData *recvData = curNode->record->recvData;
    if (curNode->record->recvData->length == 0)
    {
        return;
    }
    int get_head = can_get_head(recvData);
    while (get_head)
    {
        tidyMsg(recvData);
        // OUT_DEBUG(DEBUG,"####left#### id:%d,length:%d,head：%02x", curNode->record->sockfd, curNode->record->recvData->length, recvData->data[3]);
        int total_size = get_size(recvData->data + 3 * sizeof(int));
        int msgsize = total_size + 2 * sizeof(int);
        if (recvData->length >= msgsize + 4 * sizeof(int))
        {
            char *buffer = malloc(msgsize + 1);
            memset(buffer, 0, msgsize + 1);
            memcpy(buffer, recvData->data + 4 * sizeof(int), msgsize);
            buffer[msgsize] = '\0';
            enter_peerMsg_Queue(buffer, msgsize + 1, curNode->record->sockfd);
            int bodysize = msgsize + 4 * sizeof(int);
            int leftsize = recvData->length - bodysize;
            // free(buffer);
            // buffer = NULL;
            if (leftsize > 0)
            {
                char *lbuffer = (char *)malloc(leftsize);
                memcpy(lbuffer, recvData->data + bodysize, leftsize);
                free(recvData->data);
                recvData->data = NULL;
                recvData->data = charCopy(lbuffer, leftsize);
                recvData->length = leftsize;
                free(lbuffer);
                lbuffer = NULL;
            }
            else
            {
                free(recvData->data);
                recvData->data = NULL;
                recvData->length = 0;
            }
        }
        else
        {
             OUT_DEBUG(DEBUG,"#########can not parse node total:%d,real length:%d", msgsize + 16, recvData->length);
            break;
        }

        get_head = can_get_head(recvData);
        // OUT_DEBUG(DEBUG,"get_head_result:%d", get_head);
        if (get_head == 0)
        {
            break;
        }
    }
}

int can_get_head(RecvData *recvData)
{
    if (recvData->length > 0)
    {
        int a = 0;
        for (a = 0; a < recvData->length - 8; a++)
        {
            if (recvData->data[a] == 0x76)
            {
                if (recvData->data[a + 4] == 0x01 && recvData->data[a + 8] == 0x02)
                {
                    return 1;
                    break;
                }
            }
        }
    }
    return 0;
}